<template>
  <BasicLayout>
    <template #wrapper>
      <search-form
        :report-type="formData.reportType"
        :is-goods="true"
        :exporting="exporting"
        :expdrop="true"
        :is-export-bottom="true"
        :export-bottom-api="exportApi"
        @export="onExportReport"
        @submit="onSearchReport"
      />
      <table-pagination
        ref="table"
        :key="tableKey"
        :need-drag="true"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNo"
        border
        @handlePaginationChange="onPaginationChange"
      />
    </template>
  </BasicLayout>
</template>
<script>
import SearchForm from '@/components/business/SearchForm';
import TablePagination from '@/components/common/TablePagination';
import { getCityCommodityStockReport, exportCityCommodityStockReport } from '@/api/inventoryAnalysisApi';
import exportReportMixin from '@/components/mixins/ExportReport';
import Columns from './columnsConfig.js';

export default {
  name: 'CitySingle',
  components: {
    SearchForm,
    TablePagination
  },
  mixins: [exportReportMixin],
  data() {
    return {
      columns: Columns,
      exportApi: exportCityCommodityStockReport,
      tableData: [],
      loading: false,
      exporting: false,
      total: 0,
      pageNo: 1,
      pageSize: 10,
      formData: {},
      tableKey: 0
    };
  },
  methods: {
    /* 分页查询 */
    onPaginationChange({ current: pageNo = 1, size: pageSize = 10 } = {}) {
      this.onSearchReport({ ...this.formData, pageNo, pageSize });
    },
    /* 导出报表 */
    onExportReport(form) {
      this.exporting = true;
      exportCityCommodityStockReport({
        ...form,
        exportFormat: form.downType + 1,
        exportType: 1,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }).then(({ data: fileName }) => {
        this.onLoopFetchFileUrl('stock', fileName);
      }).catch(err => {
        this.$message.error(err);
        this.exporting = false;
      });
    },
    /* 查询报表 */
    onSearchReport(form) {
      this.loading = true;
      this.tableData = [];
      this.formData = {
        pageNo: 1,
        pageSize: 10,
        ...form
      };
      getCityCommodityStockReport(this.formData)
        .then(({ data, current, resultCode, pageSize, total }) => {
          if (resultCode === '0000') {
            this.tableData = data;
            this.total = total;
            this.pageNo = current;
            // this.pageSize = pageSize;
            const len = this.tableData.length - 1;
            this.tableData.forEach((item, index) => {
              index === len ? item.sort = '汇总' : item.sort = (current - 1) * len + (index + 1);
            });
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    }
  }
};
</script>
